package com.zzk.www.nettyServer.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzk.www.domain.Message;
import com.zzk.www.domain.User;
import com.zzk.www.nettyServer.tool.ChannelUserHolder;
import com.zzk.www.service.MessageHelperService;
import com.zzk.www.tool.common.BeanHolder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * Created by zzk on 2017/12/16.
 */


public class ZZKChatServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    //当有客户端消息写入时，该方法会自动调用
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        BeanHolder.get(MessageHelperService.class).receiveMessage(ctx, msg);
    }


    /**
     * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        BeanHolder.get(MessageHelperService.class).userConnected(ctx);
    }


    /**
     * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
     * anymore.
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        BeanHolder.get(MessageHelperService.class).userDisconnected(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
